package com.ruoyi.system.utils.rabbitMq.direct;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.ruoyi.system.domain.InterfaceLog;
import com.ruoyi.system.mapper.InterfaceLogMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Date;

/**
 * 消息发送类 - DirectSender
 */
@Component
public class DirectSender implements RabbitTemplate.ReturnCallback {
    private static final Logger logger = LoggerFactory.getLogger(DirectSender.class);

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private InterfaceLogMapper interfaceLogMapper;

    /**
     * 初始化方法，确保回调函数只被设置一次
     */
    @PostConstruct
    public void init() {
        // 设置ReturnCallback
        this.rabbitTemplate.setReturnCallback(this);

        // 设置ConfirmCallback
        this.rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if (!ack) {
                logger.error("Sender消息发送失败: " + cause + correlationData);
            } else {
                logger.info("Sender消息发送成功");
            }
        });
    }

    /**
     * 发送消息到指定队列
     * @param queueBind 队列绑定键
     * @param context 消息内容
     */
    public void send(String queueBind, String context) {
        logger.info("Sender发送内容 : {}", context);

        // 发送消息
        this.rabbitTemplate.convertAndSend(queueBind, context);

        // 日志记录
        InterfaceLog interfaceLog2 = new InterfaceLog();
        interfaceLog2.setSerialNumber(String.valueOf(new Date().getTime()));
        interfaceLog2.setStartTime(new Date());
        interfaceLog2.setInterfaceDirection("MOM->MES");
        interfaceLog2.setPacketSize("");
        interfaceLog2.setInterfaceRequest(context);
        interfaceLog2.setEndTime(new Date());
        interfaceLog2.setInterfaceResponse("");

        long be2 = DateUtil.between(interfaceLog2.getStartTime(), interfaceLog2.getEndTime(), DateUnit.MS);
        interfaceLog2.setTimeConsuming(String.valueOf(be2));
        interfaceLog2.setCreateTime(new Date());
        interfaceLog2.setInterfaceType("http");
        interfaceLog2.setInterfaceName("发隔离单信息至MES");
        interfaceLogMapper.insert(interfaceLog2);
    }

    /**
     * 消息无法被路由到队列时触发的回调
     */
    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
        logger.error("消息主体message: {}", message);
        logger.error("回复码replyCode: {}", replyCode);
        logger.error("描述replyText: {}", replyText);
        logger.error("使用的交换机exchange: {}", exchange);
        logger.error("使用的路由键routingKey: {}", routingKey);
    }
}
